/*********************************************************************************
 *      Copyright:  (C) 2024 liyi<1751425323@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  report.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(19/04/24)
 *         Author:  liyi <1751425323@qq.com>
 *      ChangeLog:  1, Release initial version on "19/04/24 11:52:28"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <mosquitto.h>
#include <netdb.h>
#include "logger.h"
#include "packet.h"
#include "proc.h"
#include "mosconnect.h"


#define DAEMON_PIDFILE "/tmp/.socket.pid"

void print_usage(char *progname)
{
	printf("%s usage:\n",progname);
	printf("example:./a.out -p 1 \n");
	printf("-H(--host):sepcify host name\n");
	printf("-p(--pattern):cloud platfrom[alyun:1 、tenxuyun:2 、 huaweiyun:3]\n");
	printf("-i(--interval):acquisition time\n");
	printf("-d(--daemon):run in daemon\n");
	printf("-h(--help):print this help infomation.\n");
	return ;
}

void callback(struct mosquitto *mosq, void *obj, int mid);

int main(int argc,char **argv)
{
	struct mosquitto	*mosq = NULL;
	bool				session = true ;
	int					get_data_flag = 0;
	int					interval = 3;
	bool				retain = true;
	int                 ch;
	int                 option = 3;
	int                 port = 1883;
	char				msg[1024];
	int                 rv = 0;
	char                *logfile = "main.log";
	char                *ini_path = "../../etc/connect.ini";
	int 				daemon_run = 0;
	time_t				cur_time;
	time_t				now_time;
	struct tm 			*local_time;
	mqtt_report_t		mqtt;
	int					rc;
	int 				*mid = NULL;
	int 				logsize = 10;
	int					loglevel = LOG_LEVEL_DEBUG;

	struct option            opts[] = {
		{"host", no_argument, NULL,'H'},
		{"pattern", required_argument, NULL,'p'},
		{"interval", no_argument, NULL,'i'},
		{"daemon", no_argument,NULL,'b'},
		{"help", no_argument, NULL,'h'},
		{NULL, 0, NULL, 0},
	};


	while((ch = getopt_long(argc , argv ,"H:p:i:h::b::" , opts , NULL)) != -1)
	{
		switch(ch)
		{
			case 'p':
				option = atoi(optarg);
				break;
			case 'i':
				interval = atoi(optarg);
				break;
			case 'b':
				daemon_run = 1;
				loglevel = LOG_LEVEL_DEBUG;
				logfile = "console";
				break;
			case 'h':
				print_usage(argv[0]);
				return 0;
			case 'H':
				break;
			default:  
				fprintf(stderr, "Unknown option: %c\n", ch);  
				print_usage(argv[0]);  
				return 1;
		}
	}

	if(log_open(logfile,  loglevel, logsize, THREAD_LOCK_NONE) < 0)
	{
		fprintf(stderr,"initial logger system failure\n");
		return -1;
	}

	install_default_signal();
#if 1
	if(check_set_program_running(daemon_run, DAEMON_PIDFILE) < 0)
	{
		goto unLink;
	}
#endif

	select_platform(ini_path, &mqtt, option);

	printf("get data success\n");

	printf("mqtt.hostname:%s,mqtt.port:%d, mqtt.clientid:%s",mqtt.hostname, mqtt.port, mqtt.clientid);
	initialize_mosquitto(&mosq, &mqtt);

#if 0
	rv = mosquitto_lib_init();
	if( rv != MOSQ_ERR_SUCCESS )
	{
		log_error("Mosq_Connect() failed: %s", strerror(errno) );
		mosquitto_lib_cleanup() ;	
		return -2;
	}

	/* create a new client instance */
	/*NULL 将作为参数传递给指定回调的用户指针，为指向struct mosquitto 结构体的指针*/
	mosq = mosquitto_new(mqtt.clientid, session, NULL) ;
	if(!mosq)
	{
		log_error("new pub_test failure:%s",strerror(errno));
		rv = -3;
		goto cleanup;
	}

	log_debug("Create mosquitto client sucessfully!");

	rv = mosquitto_username_pw_set(mosq,mqtt.username,mqtt.passwd);
	if(rv != MOSQ_ERR_SUCCESS)
	{

		log_error("set username and password failure:%s",strerror(errno));
		rv = -4;
		goto cleanup;
	}

	rv = mosquitto_connect(mosq, mqtt.hostname, mqtt.port, keep_alive_interval);

	if( rv != MOSQ_ERR_SUCCESS )
	{
		fprintf(stderr, "Error Connect: %s\n", mosquitto_strerror(rv));  
		log_error("Mosq_Connect() failed: %s", strerror(errno) );	
		rv =-5;
		goto cleanup;
	}

	log_debug("Connect %s:%d Sucessfully!", mqtt.hostname, mqtt.port);

	/*  The mosquitto'loop() function handles network events without blocking 
	 *  Network event loop processing function, continuously calling the mosquitto_loop() function to process network events by creating new threads, without blocking*/
	int loop = mosquitto_loop_start(mosq);
	
	if(loop != MOSQ_ERR_SUCCESS)
	{
		log_error("mosquitto loop error!");
		rv = -6;
		goto cleanup;
	}
#endif

	cur_time = 0;

	while(!g_signal.stop)
	{	    
		get_data_flag = 0;

		time(&now_time);
		/*local_time = localtime(&now_time);*/

		memset(msg, 0 ,sizeof(msg));

		if( (now_time - cur_time) > interval)
		{
			if(( pack_data(&mqtt, msg, sizeof(msg), option)) < 0 )
			{

				log_error("get data failure!",strerror(errno));
			}

			cur_time = now_time;
			get_data_flag = 1;

		}
		else
		{
			continue;
		}

		log_debug("%s",msg);

		printf("get data successfully\n");
		if(get_data_flag)
		{
			
			rc =  mosquitto_publish(mosq,mid, mqtt.topic,strlen(msg)+1,msg,mqtt.Qos,0) ;  
			if( rc != MOSQ_ERR_SUCCESS )
			{
				log_warn("Mosq_Publish() error");
				fprintf(stderr, "Error publishing: %s\n", mosquitto_strerror(rc));  

				//重新连接
				rc =  mosquitto_reconnect(mosq);
				if(rc != MOSQ_ERR_SUCCESS)
				{
					fprintf(stderr,"Error reconnect: %s\n", mosquitto_strerror(rc));
					log_error("Mosq_Reconnect error\n");
					rv = -7;
					goto cleanup;
				}	

			}
			else
			{
				mosquitto_publish_callback_set(mosq, callback);
			}
		}
		sleep(0.1);
	}
	
	stop_daemon_running(DAEMON_PIDFILE);

	return 0;

cleanup:
	//销毁线程
	mosquitto_loop_stop(mosq, true);
	//用于释放与 mosquitto 客户端实例关联的内存。
	mosquitto_destroy(mosq);
	//调用以释放与库关联的资源。
	mosquitto_lib_cleanup();
	log_close();
	return rv;

unLink:
	unlink(DAEMON_PIDFILE);
	log_close();
	
	return 0;
}



void callback(struct mosquitto *mosq, void *obj, int mid)
{
	log_debug("Public successfully\n");	
}	
